package top.hcode.hoj.manager.file;

import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nutz.lang.Files;
import org.nutz.lang.Strings;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import top.hcode.hoj.dao.common.FilePreviewDao;
import top.hcode.hoj.dao.course.CourseSectionDao;
import top.hcode.hoj.pojo.entity.common.FilePreview;
import top.hcode.hoj.pojo.entity.course.CourseSection;
import top.hcode.hoj.utils.AliyunOSSUtils;
import top.hcode.hoj.utils.HttpUtils;
import top.hcode.hoj.utils.PPTToImageUtil;

import java.io.File;
import java.util.List;

/**
 * @author orangej
 * @since 2025/1/2
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PPTPreviewManager {
    private final FilePreviewDao filePreviewDao;
    private final CourseSectionDao sectionDao;

    @Async
    @Transactional
    public void generateCoursePPTPreviewImage(Long sectionId, String fileUrl) {
        String previewId = IdUtil.simpleUUID();
        log.info("convert ppt to image, sectionId:{}, fileUrl:{}, previewId:{}", sectionId, fileUrl, previewId);

        String suffix = Files.getSuffix(fileUrl);
        String dir = "./preview";

        String sourceFile = dir + "/" + previewId + suffix;
        String imagePath = dir + "/" + previewId + "/";

        // 下载ppt文件
        HttpUtils.downloadFile(fileUrl, sourceFile);

        // 转为图片
        List<String> imageNameList = PPTToImageUtil.doPPT2007toImage(new File(sourceFile), imagePath);
        log.info("{} pages", imageNameList.size());

        // 上传到阿里云
        String previewUrl = null;
        for (String filename : imageNameList) {
            File file = new File(imagePath + filename);
            String key = previewId + "/" + filename;
            String url = AliyunOSSUtils.uploadFile(Files.readBytes(file), key);
            if (Strings.isBlank(previewUrl)) {
                previewUrl = url;   // 保存第一张图片
            }
        }

        // 保存 file_preview 表
        FilePreview dbo = new FilePreview();
        dbo.setId(previewId);
        dbo.setPreviewType("image");
        dbo.setPageNum(imageNameList.size());
        dbo.setPreviewUrl(previewUrl);
        dbo.setFileUrl(fileUrl);
        dbo.setFileType("ppt");

        filePreviewDao.save(dbo);

        // 更新预览状态
        CourseSection section = new CourseSection();
        section.setId(sectionId);
        section.setPreviewStatus("ready");
        section.setFilePreviewId(previewId);
        sectionDao.saveOrUpdate(section);

        // 删除本地文件
        Files.deleteFile(new File(sourceFile));
        Files.deleteDir(new File(imagePath));

        log.info("{} finished", previewId);
    }
}
